package cn.ncucode.blog.controller;

import java.util.Random;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ncucode.blog.bean.Info;
import cn.ncucode.blog.tools.EmailServ;

@Controller
@RequestMapping(value = "/email")
public class EmailController {

	EmailServ emailServ = new EmailServ(true);

	// UserService UserService;

	@RequestMapping(value = "/getRegCode")
	@ResponseBody
	public Info getRegCode(String email, HttpSession session) {
		System.out.println("开始发送验证码");
		Random random = new Random();
		String code = "";
		for (int i = 0; i < 6; i++) {
			code = code + random.nextInt(10);
		}
		try {
			System.out.println("\n 验证码: " + code + "\n");
			emailServ.sentEmail(email, "博客系统", "验证码: " + code);
			session.setAttribute(email, code);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("发送验证码失败");
			return new Info(-1, "发送验证码失败");
		}
		System.out.println("发送验证码成功");
		return new Info(0, "正常");
	}

	@RequestMapping(value = "/testEmailCode")
	@ResponseBody
	public Info testEmailCode(String email, String code, HttpSession session) {
		try {
			System.out.println("usercode = " + code);
			System.out.println("syscode = " + session.getAttribute(email));
			if (session.getAttribute(email).equals(code.trim())) {
			} else {
				throw new Exception();
			}
		} catch (Exception e) {
			return new Info(-3, "验证码错误");
		}
		return new Info(0, "正常");
	}
}
